﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) [INCLUDE APACHE 2.0 AS AN OPTION.]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.IO;
using ppscd.Configuration;

namespace ppscd
{
    public class AssemblyLoader
    {
        public static string[] Assemblies = {
                                  "Microsoft.PerformancePoint.Scorecards.Client",
                                  "Microsoft.PerformancePoint.Scorecards.DesignerPlugins",
                                  "Microsoft.PerformancePoint.Scorecards.DesignerWorkspace",
                                  "Microsoft.PerformancePoint.Scorecards.Common",
                                  "Microsoft.PerformancePoint.Scorecards.Designer.Framework",
                                  "Microsoft.SharePoint.Client",
                                  "Microsoft.SharePoint.Client.Runtime"
                              };

        public static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assemblyName = args.Name.Split(',')[0];

            if (Assemblies.Contains(assemblyName))
            {
                return Load(assemblyName);
            }

            return null;
        }

        public static Assembly Load(string assemblyName)
        {
            Console.WriteLine("Downloading assembly " + assemblyName);

            var url = PerformancePointSettings.Current.SiteCollectionUrl + "/_layouts/ppsma/1033/DesignerInstall/" + assemblyName + ".dll.deploy";

            WebClient client = new WebClient();
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

            // Use DownloadFile instead of DownloadData
            client.DownloadFile(url, assemblyName + ".dll");

            return Assembly.LoadFrom(assemblyName + ".dll");
        }

        public static void LoadAssemblies()
        {
            foreach (var assemblyName in Assemblies)
            {
                Load(assemblyName);
            }
        }
    }
}
